package com.mh.framework.security;

import com.alibaba.fastjson.JSON;
import com.mh.common.constant.HttpStatus;
import com.mh.common.core.domain.BaseResp;
import com.mh.common.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//自定义认证失败处理器
@Component
public class AuthNGImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        //通过自定义的状态码类,获取状态码401
        //public static final int UNAUTHORIZED = 401 未授权;
        Integer code = HttpStatus.UNAUTHORIZED;
        /** ServletUtils自定义工具类
         *  renderString形参: respons,String
         *  JSON.toJSONString: 任何东西都可以转换为String-->传入一个自定义的BaseResp对象
         *  BaseResp.error形参: Sting,String
         *  code为Integer类型, 但error()方法需要传入String类型, 因此通过toString()转为String
         */
        ServletUtils.renderString(response,
                JSON.toJSONString(BaseResp.error(code.toString(),"自定义认证失败处理器: 认证失败")));

    }
}
